package com.zhonghui.kf.util;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;

import java.io.IOException;
import java.io.InputStream;

public class ExcelcellsUtil {

    public static Workbook cell (InputStream in) throws Exception {
//        File f = new File("E:"+ File.separator+"test.xlsx");
//        InputStream in = new FileInputStream(f);
        Workbook wb = WorkbookFactory.create(in);
        Sheet sheet = wb.getSheetAt(0);
        if (sheet == null)
        {
            throw new IOException("文件sheet不存在");
        }
        //合并单元格数量
        for(int i = sheet.getNumMergedRegions() -1 ; i >= 0; i--) {
            //合并单元格位置(地址)
            CellRangeAddress range = sheet.getMergedRegion(i);
            //拆分单元格
            sheet.removeMergedRegion(i);
            int firstColumn = range.getFirstColumn();
            int firstRow = range.getFirstRow();
            int lastRow = range.getLastRow();
            Cell cfirst = sheet.getRow(firstRow).getCell(firstColumn);

            cfirst.setCellType(CellType.STRING);
            //填充被拆分单元格的值
            for (int m = firstRow + 1; m <= lastRow; m++) {

                Cell tc = sheet.getRow(m).getCell(firstColumn);
                tc.setCellStyle(cfirst.getCellStyle());
                tc.setCellValue(cfirst.getStringCellValue());
//                System.out.println(tc.getCellType());
//                if(tc.getCellType() ==  CellType.NUMERIC){
//                    tc.setCellValue(cfirst.getNumericCellValue());
//                }else{
//
//
//                }
            }
        }
//        FileOutputStream fos = new FileOutputStream("E:\\test1.xlsx");
//        wb.write(fos);
//        fos.close();
        return wb;
    }

}
